package com.ssii.www.myproject.web.controller;

import com.ssii.www.myproject.common.util.AjaxResult;
import com.ssii.www.myproject.common.util.LogUtils;
import com.ssii.www.myproject.common.util.UserContext;
import com.ssii.www.myproject.domain.Role;
import com.ssii.www.myproject.domain.User;
import com.ssii.www.myproject.service.UserService;
import org.apache.log4j.Logger;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

  private static final Logger logger = LogUtils.getLogger();
  @Autowired
  private UserService userService;

  @RequestMapping("/index")
  @RequiresPermissions("user:index")
  public String index() {
    return "user/index";
  }

  /**
   * 查询所有的用户
   *
   * @return
   */
  @RequestMapping("/list")
  @ResponseBody
  public List<User> list() {
    return userService.findAll();
  }

  /**
   * 根据id删除
   *
   * @param id
   * @return
   */
  @RequestMapping("/delete")
  @ResponseBody
  public AjaxResult delete(Long id) {

    if(UserContext.getUser().getId()==id){
      return new AjaxResult("不能删除自己的账户");
    }
    userService.delete(id);
    return new AjaxResult();
  }


  /**
   * 添加修改
   *
   * @return
   */
  @ResponseBody
  @PostMapping("/save")
  public AjaxResult save(@RequestBody User user) {
    System.err.println(user);
    userService.save(user);
    return new AjaxResult();
  }

  /**
   * 根据id修改状态
   *
   * @param id
   * @return
   */
  @ResponseBody
  @RequestMapping("/change")
  public AjaxResult change(Long id) {
    userService.change(id);
    return new AjaxResult();
  }

  @RequestMapping("/reset")
  @ResponseBody
  public AjaxResult reset(Long id, String password1, String rePassword) {
    if (password1 == rePassword)
      userService.reset(id, password1);
    else {
      return new AjaxResult("两次密码不一致");
    }
    return new AjaxResult();

  }

  @RequestMapping("/findOne")
  @ResponseBody
  public List<Role> findById(Long id) {
    User one = userService.findOne(id);
    List<Role> roles = one.getRoles();
    return roles;
  }

}
